/*****************************************************************
*
*	Netcare Agent Project
*		Copyright(C) 2010, Wicresoft EKA. All Rights Reserved.
*
*	Authors:
*		Miles Chen (milesch@wicresoft.com)
*		TingRong Shi (trshi@wicresoft.com)
*
*	Part of the product code depends on gSOAP under GPL license
*		Copyright(C) 2000-2010, Robert van Engelen, Genivia Inc. All Rights Reserved.
*
*****************************************************************/
#include <iostream>
#include <Windows.h>

#include "netcare.h"
#include "soapHostSoap12Service.h"
#include "Service.h"

USING_STD;
USING_NETCARE_AGENT;

#define NETCARE_SERVICE L"netcare"

#ifndef MAX_CHAR
#define MAX_CHAR 1024
#endif

SERVICE_STATUS m_ServiceStatus;
SERVICE_STATUS_HANDLE m_ServiceStatusHandle;
BOOL bRunning=true;
void WINAPI ServiceMain(DWORD argc, LPTSTR *argv);
void WINAPI ServiceCtrlHandler(DWORD Opcode);


int CService::Run(void)
{
	LogInfo(_T("Try to start netcare-agent service..."));

	SERVICE_TABLE_ENTRY dispatchTable[]= {{NETCARE_SERVICE, ServiceMain}, {NULL, NULL}};
	StartServiceCtrlDispatcher(dispatchTable);

	LogInfo(_T("Shutdown netcare-agent service..."));
	return 0;
}


void WINAPI ServiceMain(DWORD argc, LPTSTR *argv)
{
	DWORD status;
	DWORD specificError;
	m_ServiceStatus.dwServiceType = SERVICE_WIN32;
	m_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
	m_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
	m_ServiceStatus.dwWin32ExitCode = 0;
	m_ServiceStatus.dwServiceSpecificExitCode = 0;
	m_ServiceStatus.dwCheckPoint = 0;
	m_ServiceStatus.dwWaitHint = 0;

	m_ServiceStatusHandle = RegisterServiceCtrlHandler(NETCARE_SERVICE, ServiceCtrlHandler); 
	if (m_ServiceStatusHandle == (SERVICE_STATUS_HANDLE)0)
	{
		return;
	}
	m_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
	m_ServiceStatus.dwCheckPoint = 0;
	m_ServiceStatus.dwWaitHint = 0;
	if (!SetServiceStatus (m_ServiceStatusHandle, &m_ServiceStatus))
	{
	}


	HostSoap12Service host;
	soap_set_mode(&host, SOAP_C_UTFSTRING);
	LogInfo(_T("Ready to run Netcare Agent Service on port 55555"));

	bRunning=true;
	while(bRunning)
	{
		if (host.run(55555))
		{ 
			char buffer[MAX_CHAR];
			host.soap_sprint_fault(buffer, MAX_CHAR);
			LogError(buffer);
		}
	}
	return;
}

void WINAPI ServiceCtrlHandler(DWORD Opcode)
{
	switch(Opcode)
	{
	case SERVICE_CONTROL_PAUSE: 
		m_ServiceStatus.dwCurrentState = SERVICE_PAUSED;
		break;
	case SERVICE_CONTROL_CONTINUE:
		m_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
		break;
	case SERVICE_CONTROL_STOP:
		m_ServiceStatus.dwWin32ExitCode = 0;
		m_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
		m_ServiceStatus.dwCheckPoint = 0;
		m_ServiceStatus.dwWaitHint = 0;

		SetServiceStatus (m_ServiceStatusHandle,&m_ServiceStatus);
		bRunning=false;
		break;
	case SERVICE_CONTROL_INTERROGATE:
		break; 
	}
	return;
}